package com.example.logindemo.realm;

import com.example.logindemo.Pojo.User;
import com.example.logindemo.Service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class UPRealm extends AuthorizingRealm {

    @Resource
    private UserService userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        String principal = principalCollection.getPrimaryPrincipal().toString();

        String role = userService.selectRoleByUserName(principal);

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        info.addRole(role);

        return info;
    }


    //登录认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取接口请求中的用户名
        String userName = authenticationToken.getPrincipal().toString();
        //调用业务层获取User对象（数据库）
        User user = userService.selectByUserName(userName);
        //非空判断,将数据封装返回
        return new SimpleAuthenticationInfo(
                authenticationToken.getPrincipal(),
                user.getPassWord(),
                ByteSource.Util.bytes("aaa"),
                authenticationToken.getPrincipal().toString()
        );
    }
}
